package com.wang.mall.listener;

import com.alipay.api.AlipayApiException;
import com.alipay.api.internal.util.AlipaySignature;
import com.wang.mall.service.OmsOrderService;
import com.wang.mall.util.AlipayTemplate;
import com.wang.mall.vo.PayAsyncVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

@RestController
public class ListenerPayController {


    @Autowired
    AlipayTemplate alipayTemplate;

    @Autowired
    OmsOrderService orderService;

    @PostMapping("/payed/notify")
    public String handleAliPayed(PayAsyncVo payAsyncVo, HttpServletRequest request) throws AlipayApiException {

        // 只要我们收到了支付宝的异步通知，告诉我们订单支付成功，我们就返回success给支付宝，支付宝就不会在进行通知
        // 验签
        //获取支付宝POST过来反馈信息
        Map<String, String> params = new HashMap<String, String>();
        Map<String, String[]> requestParams = request.getParameterMap();
        for (Iterator<String> iter = requestParams.keySet().iterator(); iter.hasNext(); ) {
            String name = (String) iter.next();
            String[] values = (String[]) requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i]
                        : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }

        boolean b = AlipaySignature.rsaCheckV1(params, AlipayTemplate.alipay_public_key, AlipayTemplate.charset, AlipayTemplate.sign_type);
        if (b) {
            // 签名验证成功
            System.out.println("签名验证成功");
            String s = orderService.handlePayResult(payAsyncVo);
            return s;
        }
        // 只要收到支付宝的异步通知,告诉我们支付订单成功
        return "error";
    }
}
